/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.core.balancer;

import java.util.List;
import java.util.Random;
import org.apache.curator.framework.CuratorFramework;

/**
 *
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class RandomBalancer implements Balancer {
    
    private CuratorFramework zkClient;
    
    public RandomBalancer(CuratorFramework zkClient){
        this.zkClient = zkClient;
    }

    @Override
    public String select(String workerType) throws Exception{
        List<String> workers = zkClient.getChildren().forPath(workerType);
        if(workers == null){
            return null;
        }
        int size = workers.size();
        if(size == 0){
            return null;
        }
        Random r = new Random();
        int index = r.nextInt(size);
        return workers.get(index);
    }

}
